package com.xie.o2o.interceptor.shopadmin;

import com.google.common.collect.Maps;
import com.xie.o2o.util.CodeUtil;
import com.xie.o2o.util.HttpServletUtil;
import com.xie.o2o.util.JsonUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 后台管理的验证码拦截
 *
 * @create: xie
 */
public class ShopAdminVcInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = Maps.newHashMap();
        //如果前端传入不需要验证码验证的字段就直接放行
        Boolean statusChange = HttpServletUtil.getBoolean(request, "statusChange");
        if(statusChange){
            return true;
        }
        if (!CodeUtil.checkVerifyCode(request)) {
            map.put("success", false);
            map.put("errMsg", "输入了错误的验证码");

            //这里要添加reset否则会报异常，通过response返回错误信息
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(JsonUtil.obj2String(map));
            writer.close();
            writer.flush();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
